//
//  NSString+YLExtension.m
//  DoulinClient
//
//  Created by YLKJ on 2018/12/20.
//

#import "NSString+YLExtension.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (YLExtension)

- (BOOL)isNil{
    if ((self == nil) || (self == NULL) || (self.length <= 0) || [self isKindOfClass:[NSNull class]] || [self isEqualToString:@"(null)"] || [self isEqualToString:@"<null>"] || ([self trim].length <= 0)){
        return YES;
    } else {
        return NO;
    }
}
- (NSString *)nonNil{
    if ((self == nil) || (self == NULL) || (self.length <= 0) || [self isKindOfClass:[NSNull class]] || [self isEqualToString:@"(null)"] || [self isEqualToString:@"<null>"] || ([self trim].length <= 0)) {
        return @"";
    } else {
        return [NSString stringWithFormat:@"%@", [self trim]];
    }
}

+(BOOL)isempty:(NSString *)string
{
    if ([string isKindOfClass:[NSNull class]]||string==NULL||string==nil||[string isEqualToString:@"(null)"]||string.length== 0) {
        return YES;
    }else
    {
        return NO;
    }
}

#pragma mark - ------------------ 除空格和换行 ------------------
- (NSString *)trim {
    NSString * trimS = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return trimS;
}
//- (NSString *)trimWhitespace {
//    return [[self trimLeadWhitespace] trimTrailWhitespace];
//}
//- (NSString *)trimLeadWhitespace {
//    return [self trimLeadCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//}
//- (NSString *)trimTrailWhitespace {
//    return [self trimTrailCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//}
//- (NSString *)trimWhitespaceAndNewline {
//    return [[self trimLeadWhitespaceAndNewline] trimTrailWhitespaceAndNewline];
//}
//- (NSString *)trimLeadWhitespaceAndNewline {
//    return [self trimLeadCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//}
//- (NSString *)trimTrailWhitespaceAndNewline {
//    return [self trimTrailCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//}
//- (NSString *)trimLeadCharactersInSet:(NSCharacterSet *)characterSet {
//    NSUInteger location = 0;
//    NSUInteger length = [self length];
//    unichar charBuffer[length];
//    [self getCharacters:charBuffer];
//    for (location = 0; location < length; location++) {
//        if (![characterSet characterIsMember:charBuffer[location]]) {
//            break;
//        }
//    }
//    return [self substringWithRange:NSMakeRange(location, length - location)];
//}
//- (NSString *)trimTrailCharactersInSet:(NSCharacterSet *)characterSet {
//    NSUInteger location = 0;
//    NSUInteger length = [self length];
//    unichar charBuffer[length];
//    [self getCharacters:charBuffer];
//    for (length = [self length]; length > 0; length--) {
//        if (![characterSet characterIsMember:charBuffer[length - 1]]) {
//            break;
//        }
//    }
//    return [self substringWithRange:NSMakeRange(location, length - location)];
//}

#pragma mark - ------------------ 其它 ------------------
- (NSURL *)toUrl {
    return [NSURL URLWithString:self];
}
- (NSString *)md5 {
    if(self == nil || [self length] == 0) {
        return @"";
    }
    const char *cStr = [self UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *result = [NSMutableString string];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", (int)(digest[i])];
    }
    return [result copy];
}
- (NSString *)decimalFix {
#if 0  //如果有两位小数不为0则保留两位小数，如果有一位小数不为0则保留一位小数，否则显示整数
    CGFloat f = self.floatValue;
    if (fmodf(f, 1) == 0) {//如果有一位小数点
        return [NSString stringWithFormat:@"%.0f",f];
    } else if (fmodf(f * 10, 1) == 0) {//如果有两位小数点
        return [NSString stringWithFormat:@"%.1f",f];
    } else {
        return [NSString stringWithFormat:@"%.2f",f];
    }
#else  //两位小数
    return [NSString stringWithFormat:@"%.02f", self.floatValue];
#endif
}
- (NSString *)lowercaseFirstCharacter {
    NSRange range = NSMakeRange(0, 1);
    NSString *lowerFirstCharacter = [[self substringToIndex:1] lowercaseString];
    return [self stringByReplacingCharactersInRange:range withString:lowerFirstCharacter];
}
- (NSString *)uppercaseFirstCharacter {
    NSRange range = NSMakeRange(0, 1);
    NSString *upperFirstCharacter = [[self substringToIndex:1] uppercaseString];
    return [self stringByReplacingCharactersInRange:range withString:upperFirstCharacter];
}
- (NSString *)deletePrefixZeroInString {
    __block NSString * tmpStr = self;
    if (self.length > 0) {
        [self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
            if (substring.intValue != 0) {
                tmpStr = [self substringFromIndex:substringRange.location];
                *stop = YES;
            }
        }];
    }
    return tmpStr;
}

#pragma mark - ------------------ 各种验证 ------------------
- (BOOL)isValidPhone{
    NSString *Regex = @"^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$";
    NSPredicate *mobileTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [mobileTest evaluateWithObject:self];
}
- (BOOL)isValidCode{
    NSString *Regex = @"^[0-9]{6}$";
    NSPredicate *mobileTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [mobileTest evaluateWithObject:self];
}
- (BOOL)isValidPwd{
    NSString *passWordRegex = @"(^([a-zA-Z]+[0-9]+[a-zA-Z0-9]*[a-zA-Z0-9]?$))|(^([0-9]+[a-zA-Z]+[a-zA-Z0-9]*[a-zA-Z0-9]?$))";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:self];
}

- (BOOL)isValidEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    return [emailTest evaluateWithObject:self];
}
- (BOOL)isValidChinese {
    NSString *nicknameRegex = @"[\u4e00-\u9fa5]+";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:self];
}
- (BOOL)isValidEnglish {
    NSString *nicknameRegex = @"[A-Za-z]+";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:self];
}

#pragma mark - ------------------ attributedText ------------------
- (NSMutableAttributedString *)redTextFont1:(CGFloat)font1 font2:(CGFloat)font2 {
    NSString * string = [NSString stringWithFormat:@"¥%@", [self decimalFix]];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:string];
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font1] range:NSMakeRange(0, 1)];
    [attri addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:font2] range:NSMakeRange(1, string.length - 1)];
    [attri addAttribute:NSForegroundColorAttributeName value:RGB(252, 60, 60, 0) range:NSMakeRange(0, string.length)];
    return attri;
}
- (NSMutableAttributedString *)grayTextFont1:(CGFloat)font1 font2:(CGFloat)font2 {
    NSString * string = [NSString stringWithFormat:@"¥%@", [self decimalFix]];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:string];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(1, string.length - 1)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:RGB(128, 128, 128,0) range:NSMakeRange(1, string.length - 1)];
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font1] range:NSMakeRange(0, 1)];
    [attri addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:font2] range:NSMakeRange(1, string.length - 1)];
    [attri addAttribute:NSForegroundColorAttributeName value:RGB(128, 128, 128,0) range:NSMakeRange(0, string.length)];
    return attri;
}
- (NSMutableAttributedString *)blackTextFont1:(CGFloat)font1 font2:(CGFloat)font2 {
    NSString * string = [NSString stringWithFormat:@"¥%@", [self decimalFix]];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:string];
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font1] range:NSMakeRange(0, 1)];
    [attri addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:font2] range:NSMakeRange(1, string.length - 1)];
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.length)];
    return attri;
}
- (NSMutableAttributedString *)textColor:(UIColor *)color font1:(CGFloat)font1 font2:(CGFloat)font2 {
    NSString * string = [NSString stringWithFormat:@"¥%@", [self decimalFix]];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:string];
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font1] range:NSMakeRange(0, 1)];
    [attri addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:font2] range:NSMakeRange(1, string.length - 1)];
    [attri addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, string.length)];
    return attri;
}

#pragma mark - ------------------ NSDate ------------------
+ (NSDate *)dateFromString:(NSString *)string {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *destDate= [formatter dateFromString:string];
    return destDate;
}
+ (NSString *)stringFromDate:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *destDateString = [formatter stringFromDate:date];
    return destDateString;
}
+ (NSString *)timeFromInterval:(NSTimeInterval)time {
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [formatter stringFromDate:date];
}
+ (NSString *)currentDate {
    NSDate * date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * destDateString = [formatter stringFromDate:date];
    return destDateString;
}
+ (NSString *)dateWithFormat:(NSString *)format {
    return nil;
}

#pragma mark - ------------------ <#note#> ------------------
- (NSString*)decodeURLString {
    //处理空格
    NSString *result_plus = [self stringByReplacingOccurrencesOfString:@"+" withString:@"%20"];
    NSString* result = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)result_plus, CFSTR(""), kCFStringEncodingUTF8));
    return result;
}
- (NSString *)encodedURLParameterString {
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR(":/=,!$&'()*+;[]@#?"), kCFStringEncodingUTF8));
    return result;
}

#pragma mark - ------------------ <#note#> ------------------
- (CGSize)mh_sizeWithFont:(UIFont *)font {
    CGSize theSize;
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    theSize = [self sizeWithAttributes:attributes];
    // 向上取整
    theSize.width = ceil(theSize.width);
    theSize.height = ceil(theSize.height);
    return theSize;
}
- (CGSize)mh_sizeWithFont:(UIFont *)font limitSize:(CGSize)limitSize {
    CGSize theSize;
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    CGRect rect = [self boundingRectWithSize:limitSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil];
    theSize.width = ceil(rect.size.width);
    theSize.height = ceil(rect.size.height);
    return theSize;
}
- (CGSize)mh_sizeWithFont:(UIFont *)font limitWidth:(CGFloat)limitWidth {
    return [self mh_sizeWithFont:font limitSize:CGSizeMake(limitWidth, MAXFLOAT)];
}
- (CGFloat)widthForSizeFont:(UIFont *)font andHeight:(float)height {
    NSDictionary *attribute = @{NSFontAttributeName:font};
    CGSize textSize = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return textSize.width;
}
- (CGFloat)heightForSizeWithFont:(UIFont *)font andWidth:(float)width {
    NSDictionary *attribute = @{NSFontAttributeName:font};
    CGSize textSize = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return textSize.height;
}

@end

